package com.yunyu.demo;

import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.yunyu.camera.opengl.LTRTCFilterManager;
import com.yunyu.camera.opengl.LTVideoFrameFilter;
import com.yunyu.camera.opengl.render.GLYUVView;
import com.yunyu.camera.webrtc.CameraHelper;

import org.webrtc.VideoFrame;

import java.nio.ByteBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class CameraBufferActivity extends AppCompatActivity implements GLSurfaceView.Renderer {
    private final String TAG = CameraBufferActivity.class.getSimpleName();
    /**
     * 相机数据帮助类
     */
    CameraHelper cameraHelper;
    /**
     * 视频处理滤镜
     */
    LTVideoFrameFilter frameFilter;
    /**
     * 预览view
     */
    GLSurfaceView surfaceView;

    GLYUVView glRender;

    CameraActivityHelper cameraActivityHelper;

    @Override
    public void onSurfaceCreated(GL10 gl10, EGLConfig eglConfig) {
        Log.d(TAG, "onSurfaceCreated: ");
        glRender = new GLYUVView(getApplicationContext(), GLYUVView.YUVType.I420);
        glRender.onSurfaceCreated(gl10,eglConfig);
    }

    @Override
    public void onSurfaceChanged(GL10 gl10, int width, int height) {
        Log.d(TAG, String.format("onSurfaceChanged: width = %d height = %d",width,height));
        glRender.onSurfaceChanged(gl10,width,height);
    }

    @Override
    public void onDrawFrame(GL10 gl10) {
        glRender.onDrawFrame(gl10);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.frag_camera);

        cameraActivityHelper = new CameraActivityHelper(this);

        //测试离屏渲染
        testOffRender();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (cameraHelper != null){
            cameraHelper.closeCamera();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (cameraHelper !=null)
            cameraHelper.destroy();
        if (frameFilter != null)
            frameFilter.destroy();
    }

    void testOffRender(){
        //模拟渲染
        surfaceView = new GLSurfaceView(this);
        surfaceView.setPreserveEGLContextOnPause(true);
        surfaceView.setEGLContextClientVersion(2);
        surfaceView.setEGLConfigChooser(8, 8, 8, 8, 16, 0); // Alpha used for plane blending.
        surfaceView.setRenderer(this);
        surfaceView.setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
        surfaceView.setWillNotDraw(false);

        //设置surfaceView布局
        ConstraintLayout frameLayout = findViewById(R.id.glCameraBox);
//        int width = ScreenUtil.INSTANCE.getWidth();
        int width = getResources().getDisplayMetrics().widthPixels;
        int height = (int)(width * 16f / 9f);
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(width,height);
        frameLayout.addView(surfaceView,0, layoutParams);

        //构造frameFilter
        frameFilter = new LTVideoFrameFilter(getApplicationContext());
        //开启纹理输出模式 默认VideoFrame输出模式
//        frameFilter.setTextureOutMode();
        frameFilter.setListener(new LTVideoFrameFilter.Callback() {
            @Override
            public void didFilterVideoFrameDone(VideoFrame frame) {
                //监听处理后的视频帧加载surfaceView显示
                VideoFrame.I420Buffer i420Buffer = frame.getBuffer().toI420();
                ByteBuffer srcBufferY = i420Buffer.getDataY();
                ByteBuffer srcBufferU = i420Buffer.getDataU();
                ByteBuffer srcBufferV = i420Buffer.getDataV();
                glRender.loadI420Buffer(srcBufferY,srcBufferU,srcBufferV,i420Buffer.getWidth(),i420Buffer.getHeight());
                glRender.setShowRotate(360 - frame.getRotation(),0,0,1);
                surfaceView.requestRender();

                i420Buffer.release();
            }

            @Override
            public void onFaceDetectedState(boolean hasFace) {

            }
        });

        //构建控制页面
        LTRTCFilterManager filterManager = frameFilter.getFilterManager();
        cameraActivityHelper.testControl(filterManager);

        //frameFilter关联相机数据
        createVideoDateIn(frameFilter);

        //切换后置摄像头
        CheckBox backCameraCB = findViewById(R.id.glBackCamera);
        backCameraCB.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked){
                cameraHelper.flipCamera(CameraHelper.Direction.BACK);
//                ltglRenderManager.flipCamera(LTGLRenderManager.CameraDirection.BACK);
            }
            else {
                cameraHelper.flipCamera(CameraHelper.Direction.FRONT);
//                ltglRenderManager.flipCamera(LTGLRenderManager.CameraDirection.FRONT);
            }
        });
    }

    private void createVideoDateIn(LTVideoFrameFilter frameFilter){
        //构造摄像头输入
        cameraHelper = new CameraHelper(getApplicationContext(), true, new CameraHelper.CameraHelperListener() {
            @Override
            public void onCameraSwitchCompleted() {

            }

            @Override
            public void onCameraFrame(ByteBuffer yByteBuffer, ByteBuffer uvByteBuffer, int width, int height, long timestampNs, int rotate) {
                frameFilter.syncFilterNV21ByteBuffer(yByteBuffer, uvByteBuffer, width, height, timestampNs, rotate);
            }
        });
        //打开摄像头
        cameraHelper.openCamera(CameraHelper.Direction.FRONT);
    }
}
